import {setStore, getStore} from '@/utils/store'
import {
  login,
  logout,
  getInfo,
  getdictionary,
  getVehicleDictionary
} from '@/api/user'
// import { getVehicleDictionary } from '@/api/bookingManagement'
import {
  loadprovincecitycounty
} from '@/api/service'
import {
  getToken,
  setToken,
  removeToken,
  getLoginFlag,
  setLoginFlag,
  removeLoginFlag,
  getName,
  setName,
  removeName,
  removeMenu,
  getUserId,
  removeUserId,
  setUserInfo,
  getUserInfo,
  removeUserInfo,
  setMenu,
  getMenu,
  getProvinceCityCounty,
  setUserId,
  setProvinceCityCounty,
  removeProvinceCityCounty
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import qs from 'qs'
const state = {
  userInfo: getUserInfo(),
  token: getToken(),
  name: getName(),
  avatar: '',
  loginFlag: getLoginFlag(), //系统标志
  page: [],
  expires_in: '',
  dictionary: getStore({name: 'dictionary'}) || {}, //字典数据
  businessCode: "", //业务编码，输入再次切换时
  provinceCityCounty: getProvinceCityCounty() //省市区县
}

const mutations = {
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_LOGINFLAG: (state, flag) => {
    state.loginFlag = flag;
  },
  SET_PAGE: (state, page) => {
    state.page = page
  },
  SET_DICTIONARY: (state, dictionary) => {
    state.dictionary = dictionary
    setStore({name: 'dictionary', content: state.dictionary, type: 'session'})
  },
  SET_EXPIRES_IN: (state, expires_in) => {
    state.expires_in = expires_in
  },
  SET_BUSINESSCODE: (state, businessCode) => {
    state.businessCode = businessCode
  },
  SET_PROVINCECITYCOUNTY: (state, provinceCityCounty) => {
    state.provinceCityCounty = provinceCityCounty
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      Flag
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password
      }).then(response => {
        if (response && response.data) {
          const {
            data
          } = response
          //登录用户信息
          commit('SET_USERINFO', data)
          commit('SET_TOKEN', data.token)
          commit('SET_NAME', data.fullName)
          commit('SET_EXPIRES_IN', data.expiresIn)
          removeToken()
          setUserInfo(data)
          setToken(data.token)
          setName(data.jobNo)
          //保存登录系统标志，以备刷新
          removeLoginFlag()
          commit('SET_LOGINFLAG', Flag)
          setLoginFlag(Flag);
          resolve(data)
        } else {
          reject(response)
        }

      }).catch(error => {
        reject(error)
      })
    })
  },

  // 提供token，系统标志，获取页面及按钮权限
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // let data={'sysflag':state.flag};
      let postData = {
        'systemCode': 'api'
      };
      getInfo(postData).then(response => {
        if (response && response.data) {
          const {
            data
          } = response
          if (!data) {
            reject('验证失败,请重新登录')
          }
          //调试页面
          //返回页面及按钮权限
          if (data && data.length > 0) {
            let item;
            //处理首页的路径
            for (let i = 0; i < data.length; i++) {
              item = data[i];
              if (item.path == '/') {
                let redStr = item.redirect;
                redStr = redStr.substring(redStr.lastIndexOf('/'));
                item.hidden = true;
                item.redirect = redStr;
                item['component'] = 'Layout';
                delete item.meta;
                delete item.buttons;
                delete item.children;
              }
              //非主页
              else {
                item['component'] = 'Layout';
                let children = item.children;
                let redirect = item.redirect;
                if (redirect) {
                  item.redirect = redirect.substring(redirect.lastIndexOf('/'));
                }
                if (children && children.length > 0) {
                  let itemC;
                  for (let j = 0; j < children.length; j++) {
                    itemC = children[j];
                    itemC.path = itemC.path.substring(itemC.path.lastIndexOf('/'));
                    itemC.name = 'home' + itemC.name;
                    delete itemC.redirect;
                  }
                }
              }
              //处理chilren
            }
          }
          const page = data
          commit('SET_PAGE', page)
          setMenu({
            menu: page
          })
          resolve(data)
        } else {
          reject(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout({
        token: state.token
      }).then((res) => {
        if (res.code === 1) {
          commit('SET_TOKEN', '')
          removeToken()
          removeName()
          removeMenu()
          resetRouter()
          //清除省市区县缓存
          removeProvinceCityCounty()
          commit('SET_BUSINESSCODE', "")
          resolve(res)
        } else {
          reject()
        }

      }).catch(error => {
        reject(error)
      })
    })
  },
  // 登录系统标志
  setFlag({
    commit
  }, flag) {
    return new Promise(resolve => {
      commit('SET_FLAG', flag)
      resolve()
    })
  },
  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_PAGE', [])
      removeToken()
      resolve()
    })
  },
  // 字典数据
  getdictionary({
    commit,
    state
  }) {
    // if (JSON.stringify(state.dictionary) != "{}") {
    //   return state.dictionary
    // }
    let node_type=''
    if(state.userInfo.organizationType==2){
      node_type='gw_node_type'
    }
    const arr = [`${node_type}`,'gm_grave_type','storage_node_type',"cells_type","burial_certificate_unit","cremation_charge_type","sex", "sex_simple", "age_type", "negotiator_user", "certificates", "funeral_certificate_unit", "ashes_treatment", "nationality", "domicile", "nation", "type_of_death", "cremation_type", "remains_state", "cause_of_death", "huimin_region", "exemption_type", "mode_with_carry", "relationship_with_decea", "funeral_unit_type", "agent_type", "negotiator_user", "relationship_with_deceased", "transport_car_type", "transport_car_use", "transport_car_task_status", "equipment_type", "refrigerated_state", "hall_business_type", "hall_status", "wake_mourn_type", "farewell_mourn_type", "ashes_treatment", "furnace_type", "cremation_task_status", "treatment_of_ashes", "ashes_whereabouts", "cremation_certificate_printing_operation_type", "document_type", "settle_type", "pay_type"]
    return new Promise((resolve, reject) => {
      getdictionary(arr).then((response) => {
        if (response) {
          const {
            data
          } = response
          // console.log('用户字典ssss',response)
          for (let item in data) {
            if (data[item]) {
              data[item].forEach((n) => {
                if (!n.disableState) {
                  n.disableState = false
                } else {
                  n.disableState = true
                }
              })
            }

          }
          //给字典赋值
          commit('SET_DICTIONARY', data)
          // removedictionary();
          // setdictionary(data)
          // console.log(state.dictionary)
          resolve(data)
        } else {
          reject(response)
        }

      }).catch(error => {
        reject(error)
      })
    })
  },
  // 车辆字典数据
  getVehicleDictionary({
    commit,
    state
  }) {
    if (JSON.stringify(state.dictionary) != "{}") {
      return state.dictionary
    }
    const arr = {
      dictTypeCodes: [
        "body_deposited_type",
        "transport_car_type",
        "rec_relation_type",
        "rec_source_type",
        "relationship_with_deceased",
        "transport_car_use",
        "rec_source_type",
        "rec_task_state_type"
      ],
      id: 0,
      serviceItemTypeCode: "use_in_rec_info",
      userRoleCodes: ["transport_task_driver_user", "transport_task_porter"]
    }
    return new Promise((resolve, reject) => {
      getVehicleDictionary(arr).then((response) => {
        if (response) {
          const {
            data
          } = response
          resolve(data)
        } else {
          reject(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 加载省市区县
  getProvinceCityCounty({
    commit,
    state
  }) {
    if (JSON.stringify(state.provinceCityCounty) != "[]") {
      return state.provinceCityCounty
    }
    return new Promise((resolve, reject) => {
      //获得省市区县
      loadprovincecitycounty(null).then((response) => {
        if (response) {
          const {
            data
          } = response
          //设置省市区县
          commit('SET_PROVINCECITYCOUNTY', data)
          //保存到缓存中
          let obj = {
            provinceCityCounty: data
          };
          setProvinceCityCounty(obj);
          resolve(data)
        } else {
          reject(response)
        }

      }).catch(error => {
        reject(error)
      })
    })
  },
  //业务编码保存到缓存中
  setbusinessCode({
    commit,
    state
  }, data) {
    commit('SET_BUSINESSCODE', data)
  },

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
